package com.qaml.mes.device.domain.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.earth.except.error.BusinessException;
import com.earth.page.PageResponse;
import com.earth.user.AuthSsoContext;
import com.earth.user.SsoLoginUser;
import com.google.common.collect.Lists;
import com.qaml.mes.device.api.*;
import com.qaml.mes.device.dao.*;
import com.qaml.mes.device.dao.mapper.CheckUpkeepRecordMapper;
import com.qaml.mes.device.repository.*;
import com.qaml.mes.device.utils.DateUtils;
import com.qaml.mes.device.utils.IdGenerateUtils;
import com.qaml.mes.device.domain.convert.CheckUpkeepRecordConvert;
import com.qaml.mes.device.domain.convert.CheckUpkeepRecordItemConvert;
import com.qaml.mes.device.domain.convert.CheckUpkeepUserConvert;
import com.qaml.mes.device.dto.eqp.*;
import com.qaml.mes.device.enums.*;
import com.qaml.mes.device.vo.eqp.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.qaml.mes.device.config.ThreadPoolConfiguration.DEVICE_THREAD_POOL_EXECUTOR;

/**
 * <p>
 * 检保记录表 服务实现类
 * </p>
 *
 * @author leikai
 * @since 2024-02-27
 */
@Service
@Slf4j
public class CheckUpkeepRecordServiceImpl implements CheckUpkeepRecordService {


    @Resource
    private CheckUpkeepRecordRepository checkUpkeepRecordRepository;

    @Resource
    private CheckUpkeepUserRepository checkUpkeepUserRepository;

    @Resource
    private CheckUpkeepRecordItemRepository checkUpkeepRecordItemRepository;

    @Resource
    private EqpRepairRepository eqpRepairRepository;

    @Resource
    private EqpAttachmentRepository eqpAttachmentRepository;

    @Resource
    private CheckUpkeepRecordItemService checkUpkeepRecordItemService;

    @Resource
    private CheckUpkeepRecordRecheckService checkUpkeepRecordRecheckService;

    @Resource
    private CheckUpkeepMessageRepository checkUpkeepMessageRepository;

    @Resource
    private CheckUpkeepRecordRecheckRepository checkUpkeepRecordRecheckRepository;

    @Resource
    private HolidayApplyRepository holidayApplyRepository;

    @Resource
    private CheckUpkeepUserService checkUpkeepUserService;


    @Resource
    private TransactionTemplate transactionTemplate;

    @Autowired
    private EqpInfoRepository eqpInfoRepository;


    private static final List<String> CAN_COMMIT = Arrays.asList(CheckUpkeepStatusEnum.NO_COMMIT.getType(), CheckUpkeepStatusEnum.TURN_DOWN.getType());

    private static final List<String> CAN_RECHECK = Arrays.asList(CheckUpkeepStatusEnum.RECHECKING.getType(), CheckUpkeepStatusEnum.ARCHIVIST_TURN_DOWN.getType());

    @Override
    public HomePageCountVO countDoing(String userId) {
        // 待维修
        HomePageCountVO homePageCountVO = new HomePageCountVO();
        Long repairCount = eqpRepairRepository.countByUserId(userId);
        homePageCountVO.setRepairCount(repairCount);
        Integer checkCount = 0;
        Integer upkeepCount = 0;
        Integer archivistCount = 0;
        // 点检待处理
        List<CheckUpkeepUserDO> checkUserDOList = checkUpkeepUserRepository.getByType(userId, null);
        if (!checkUserDOList.isEmpty()) {
            List<String> checkIds = checkUserDOList.stream().map(CheckUpkeepUserDO::getCheckUpkeepId).collect(Collectors.toList());
            List<CheckUpkeepRecordDO> byCheckUpkeepId = checkUpkeepRecordRepository.getByCheckUpkeepId(checkIds);
            if (!CollectionUtils.isEmpty(byCheckUpkeepId)) {
                //点检待处理
                List<CheckUpkeepRecordDO> checkCounts = byCheckUpkeepId.stream().filter(item -> item.getType().equals(CheckUpkeepTypeEnum.CHECK.getType()) &&
                        (CheckUpkeepStatusEnum.NO_COMMIT.getType().equals(item.getStatus())
                                || CheckUpkeepStatusEnum.RECHECKING.getType().equals(item.getStatus()))).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(checkCounts)) {
                    checkCount = checkCounts.size();
                }
                List<CheckUpkeepRecordDO> upkeepCounts = byCheckUpkeepId.stream().filter(item -> item.getType().equals(CheckUpkeepTypeEnum.UPKEEP.getType()) &&
                        (CheckUpkeepStatusEnum.NO_COMMIT.getType().equals(item.getStatus())
                                || CheckUpkeepStatusEnum.RECHECKING.getType().equals(item.getStatus()))).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(upkeepCounts)) {
                    upkeepCount = upkeepCounts.size();
                }
                List<CheckUpkeepRecordDO> archivistCounts = byCheckUpkeepId.stream()
                        .filter(item -> CheckUpkeepStatusEnum.ARCHIVIST.getType().equals(item.getStatus()))
                        .collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(archivistCounts)) {
                    archivistCount = archivistCounts.size();
                }
            }
        }
        homePageCountVO.setCheckCount(checkCount);
        homePageCountVO.setUpkeepCount(upkeepCount);
        homePageCountVO.setArchivistCount(archivistCount);
        return homePageCountVO;
    }

    @Override
    public PageResponse<CheckUpkeepRecordAppVO> orderList(CheckUpkeepRecordAppDTO recordAppDTO) {

        // 1、获取检保记录的分页数据
        IPage<CheckUpkeepRecordDO> recordDOIPage = checkUpkeepRecordRepository.pageList(recordAppDTO.getPage(), recordAppDTO.getPageSize(), recordAppDTO);
        if (recordDOIPage == null || CollectionUtils.isEmpty(recordDOIPage.getRecords())) {
            return new PageResponse<>(0, null, recordAppDTO);
        }
        List<CheckUpkeepRecordDO> records = recordDOIPage.getRecords();
        // 2、将查询到的检保记录转换为VO对象
        List<CheckUpkeepRecordAppVO> checkUpkeepRecordAppVOS = CheckUpkeepRecordConvert.INSTANCE.do2AppVoList(records);

        // 3、对检保记录VO对象集合进行处理   提取checkUpkeepId(检保项目编号)
        List<String> checkUpkeepIds = checkUpkeepRecordAppVOS.stream().map(CheckUpkeepRecordAppVO::getCheckUpkeepId).collect(Collectors.toList());
        // 3.1、根据checkUpkeepId（检保项目编号），查询到所有的人员
        List<CheckUpkeepUserDO> checkUpkeepUserDOS = checkUpkeepUserRepository.getCheckUserByCheckUpkeepIds(checkUpkeepIds, null);
        // 3.2、存为一个Map   // 通过检保项目编号 CheckUpkeepId分组
        Map<String, List<CheckUpkeepUserDO>> userMap;
        if (!CollectionUtils.isEmpty(checkUpkeepUserDOS)) {
            userMap = checkUpkeepUserDOS.stream().collect(Collectors.groupingBy(CheckUpkeepUserDO::getCheckUpkeepId));
        } else {
            userMap = new HashMap<>();
        }

        checkUpkeepRecordAppVOS.forEach(checkUpkeepRecordAppVO -> {
            //图片查询
            List<EqpAttachmentDO> attachmentDOS = eqpInfoRepository.getAttachmentByEqpId(checkUpkeepRecordAppVO.getEqpId(), AttachmentTypeEnum.IMAGE.getType(), 1);
            if (!CollectionUtils.isEmpty(attachmentDOS)) {
                checkUpkeepRecordAppVO.setImageUrl(attachmentDOS.get(0).getAttachmentUrl());
            }

            CheckUpkeepStatusEnum checkUpkeepStatusEnum = CheckUpkeepStatusEnum.ofType(checkUpkeepRecordAppVO.getStatus());
            checkUpkeepRecordAppVO.setStatusDesc(checkUpkeepStatusEnum == null ? null : checkUpkeepStatusEnum.getDesc());
            List<CheckUpkeepUserDO> checkUpkeepUserDOList = userMap.get(checkUpkeepRecordAppVO.getCheckUpkeepId());
            if (CollectionUtils.isEmpty(checkUpkeepUserDOList)) {
                return;
            }
            // 检查人
            List<CheckUpkeepUserDO> checkList = checkUpkeepUserDOList.stream()
                    .filter(checkUpkeepUserDO -> checkUpkeepUserDO.getPersonType().equals(CheckUpkeepUserTypeEnum.CHECK.getType()))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(checkList)) {
                List<CheckUpkeepUserVO> voList = CheckUpkeepUserConvert.INSTANCE.toVOList(checkList);
                checkUpkeepRecordAppVO.setCheckUserList(voList);
            }

            List<CheckUpkeepUserDO> recheckList = checkUpkeepUserDOList.stream()
                    .filter(checkUpkeepUserDO -> checkUpkeepUserDO.getPersonType().equals(CheckUpkeepUserTypeEnum.RECHECK.getType()))
                    .collect(Collectors.toList());
            // 复核人
            if (!CollectionUtils.isEmpty(recheckList)) {
                List<CheckUpkeepUserVO> voList = CheckUpkeepUserConvert.INSTANCE.toVOList(recheckList);
                checkUpkeepRecordAppVO.setRecheckUserList(voList);
            }
            List<CheckUpkeepUserDO> archiveList = checkUpkeepUserDOList.stream()
                    .filter(checkUpkeepUserDO -> checkUpkeepUserDO.getPersonType().equals(CheckUpkeepUserTypeEnum.ARCHIVIST.getType()))
                    .collect(Collectors.toList());
            // 归档人
            if (!CollectionUtils.isEmpty(archiveList)) {
                List<CheckUpkeepUserVO> voList = CheckUpkeepUserConvert.INSTANCE.toVOList(archiveList);
                checkUpkeepRecordAppVO.setArchiveUserList(voList);
            }
            // 设置权限操作
            hasEditAuth(checkUpkeepRecordAppVO);
        });
        return new PageResponse<>(recordDOIPage.getTotal(), checkUpkeepRecordAppVOS, recordAppDTO);
    }

    private void hasEditAuth(CheckUpkeepRecordAppVO checkUpkeepRecordAppVO) {
        String currentUserId = AuthSsoContext.getCurrentUserId();
        // 审核中  归档驳回  判断当前登录人是否可以审核
        if (checkUpkeepRecordAppVO.getStatus().equals(CheckUpkeepStatusEnum.RECHECKING.getType()) || checkUpkeepRecordAppVO.getStatus()
                .equals(CheckUpkeepStatusEnum.ARCHIVIST_TURN_DOWN.getType())) {
            // 复核人
            if (checkUpkeepRecordAppVO.getRecheckUserId().equals(currentUserId)) {
                checkUpkeepRecordAppVO.setCanRecheck(Boolean.TRUE);
            }
            // 已通过 判断当前登录人是否可以归档
        } else if (checkUpkeepRecordAppVO.getStatus().equals(CheckUpkeepStatusEnum.PASSED.getType())) {
            // 归档人
            if (checkUpkeepRecordAppVO.getArchiveUserId().equals(currentUserId)) {
                checkUpkeepRecordAppVO.setCanArchive(Boolean.TRUE);
            }
            // 未提交 判断当前登录人是否可以提交
        } else if (checkUpkeepRecordAppVO.getStatus().equals(CheckUpkeepStatusEnum.NO_COMMIT.getType())) {
            List<CheckUpkeepUserVO> checkUserList = checkUpkeepRecordAppVO.getCheckUserList();
            if (!CollectionUtils.isEmpty(checkUserList)) {
                List<String> userIds = checkUserList.stream().map(CheckUpkeepUserVO::getUserId).collect(Collectors.toList());
                if (userIds.contains(currentUserId)) {
                    checkUpkeepRecordAppVO.setCanCheck(Boolean.TRUE);
                }
            }
            // 已驳回 判断当前登录人是否可以提交
        } else if (checkUpkeepRecordAppVO.getStatus().equals(CheckUpkeepStatusEnum.TURN_DOWN.getType())) {
            // 点检人
            if (checkUpkeepRecordAppVO.getCheckUpkeepUserId().equals(currentUserId)) {
                checkUpkeepRecordAppVO.setCanCheck(Boolean.TRUE);
            }
        }
    }

    /**
     * 检保快速提交
     *
     * @param checkUpkeepRecordDTO
     */
    @Override
    public void checkUpkeepFastCommit(CheckUpkeepRecordDTO checkUpkeepRecordDTO) {
        // 获取检保记录
        CheckUpkeepRecordDO checkUpkeepRecordDO = checkUpkeepRecordRepository.getById(checkUpkeepRecordDTO.getId());
        if (checkUpkeepRecordDO == null || !CAN_COMMIT.contains(checkUpkeepRecordDO.getStatus())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        List<CheckUpkeepUserDO> checkUserByCheckUpkeepIds = checkUpkeepUserRepository.getCheckUserByCheckUpkeepIds(Collections.singletonList(checkUpkeepRecordDO.getCheckUpkeepId()), CheckUpkeepUserTypeEnum.CHECK.getType());
        if (CollectionUtils.isEmpty(checkUserByCheckUpkeepIds)) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        List<String> userIds = checkUserByCheckUpkeepIds.stream().map(CheckUpkeepUserDO::getUserId).collect(Collectors.toList());
        SsoLoginUser ssoLoginUser = AuthSsoContext.getSsoLoginUser();
        if (!userIds.contains(ssoLoginUser.getUserId())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        checkUpkeepRecordDO.setStatus(CheckUpkeepStatusEnum.RECHECKING.getType());
        checkUpkeepRecordDO.setCheckUpkeepUserId(ssoLoginUser.getUserId());
        checkUpkeepRecordDO.setCheckUpkeepUserName(ssoLoginUser.getUserName());
        checkUpkeepRecordDO.setCheckUpkeepCommitDate(new Date());
        checkUpkeepRecordDO.setRecheckUserId(checkUpkeepRecordDTO.getRecheckUserId());
        checkUpkeepRecordDO.setRecheckUserName(checkUpkeepRecordDTO.getRecheckUserName());
        checkUpkeepRecordDO.setErrResult(0);
        // 修改检保单状态
        checkUpkeepRecordRepository.updateById(checkUpkeepRecordDO);
        // 修改检保条目状态
        checkUpkeepRecordItemRepository.updateStatusByRecordId(checkUpkeepRecordDO.getId());
        // 发送审核消息
        sendCheckUpkeepMessage(checkUpkeepRecordDO, checkUpkeepRecordDO.getType(), CheckUpkeepStatusEnum.RECHECKING.getType());


    }

    /**
     * 检保提交
     *
     * @param checkUpkeepRecordDTO
     */
    @Override
    public void checkUpkeepCommit(CheckUpkeepRecordDTO checkUpkeepRecordDTO) {
        CheckUpkeepRecordDO checkUpkeepRecordDO = checkUpkeepRecordRepository.getById(checkUpkeepRecordDTO.getId());
        if (checkUpkeepRecordDO == null || !CAN_COMMIT.contains(checkUpkeepRecordDO.getStatus())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        List<CheckUpkeepUserDO> checkUserByCheckUpkeepIds = checkUpkeepUserRepository.getByCheckUpkeepIdAndStatus(checkUpkeepRecordDO.getCheckUpkeepId(), null);
        if (CollectionUtils.isEmpty(checkUserByCheckUpkeepIds)) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        List<String> userIds = checkUserByCheckUpkeepIds.stream().map(CheckUpkeepUserDO::getUserId).collect(Collectors.toList());
        SsoLoginUser ssoLoginUser = AuthSsoContext.getSsoLoginUser();
        if (!userIds.contains(ssoLoginUser.getUserId())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        String type = checkUpkeepRecordDO.getType();
        String checkUpkeepId = checkUpkeepRecordDO.getCheckUpkeepId();
        Date checkUpkeepDate = checkUpkeepRecordDO.getCheckUpkeepDate();
        checkUpkeepRecordDO = CheckUpkeepRecordConvert.INSTANCE.dto2Do(checkUpkeepRecordDTO);
        checkUpkeepRecordDO.setCheckUpkeepCommitDate(new Date());
        // 更新检保条目
        // 修改检保单状态
        CheckUpkeepRecordDO finalCheckUpkeepRecordDO = checkUpkeepRecordDO;
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                if (!CAN_COMMIT.contains(finalCheckUpkeepRecordDO.getStatus())) {
                    throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
                }
                updateItem(checkUpkeepRecordDTO, finalCheckUpkeepRecordDO);
                checkUpkeepRecordRepository.updateById(finalCheckUpkeepRecordDO);
                CheckUpkeepRecordRecheckDO checkUpkeepRecordRecheckDO =
                        CheckUpkeepRecordConvert.INSTANCE.buildRecordRecheck(finalCheckUpkeepRecordDO, CheckUpkeepRecordRecheck.HandlerType.CHECK_UPKEEP);
                checkUpkeepRecordRecheckDO.setHandleOpRemark(CheckUpkeepRecordRecheck.HandleOpRemark.CHECK_UPKEEP_COMMIT.getDesc());
                checkUpkeepRecordRecheckRepository.insert(checkUpkeepRecordRecheckDO);
            }
        });
        checkUpkeepRecordDO.setCheckUpkeepId(checkUpkeepId);
        checkUpkeepRecordDO.setCheckUpkeepDate(checkUpkeepDate);
        // 发送审核消息
        sendCheckUpkeepMessage(checkUpkeepRecordDO, type, CheckUpkeepStatusEnum.RECHECKING.getType());
    }

    @Override
    public void checkUpkeepCommitRepair(CheckUpkeepRecordDTO checkUpkeepRecordDTO) {
        CheckUpkeepRecordDO checkUpkeepRecordDO = checkUpkeepRecordRepository.getById(checkUpkeepRecordDTO.getId());
        if (checkUpkeepRecordDO == null) {
            throw new BusinessException(BizErrorEnums.NOT_DATA);
        }
        if (!CAN_COMMIT.contains(checkUpkeepRecordDO.getStatus())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        List<CheckUpkeepUserDO> checkUserByCheckUpkeepIds = checkUpkeepUserRepository.getCheckUserByCheckUpkeepIds(Collections.singletonList(checkUpkeepRecordDO.getCheckUpkeepId()), CheckUpkeepUserTypeEnum.CHECK.getType());
        if (CollectionUtils.isEmpty(checkUserByCheckUpkeepIds)) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        List<String> userIds = checkUserByCheckUpkeepIds.stream().map(CheckUpkeepUserDO::getUserId).collect(Collectors.toList());
        SsoLoginUser ssoLoginUser = AuthSsoContext.getSsoLoginUser();
        if (!userIds.contains(ssoLoginUser.getUserId())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        String type = checkUpkeepRecordDO.getType();
        String checkUpkeepId = checkUpkeepRecordDO.getCheckUpkeepId();
        checkUpkeepRecordDO = CheckUpkeepRecordConvert.INSTANCE.dto2Do(checkUpkeepRecordDTO);
        checkUpkeepRecordDO.setCheckUpkeepId(checkUpkeepId);
        checkUpkeepRecordDO.setCheckUpkeepDate(checkUpkeepRecordDO.getCheckUpkeepDate());
        // 更新检保条目
        checkUpkeepRecordDO.setCheckUpkeepCommitDate(new Date());
        CheckUpkeepRecordDO finalCheckUpkeepRecordDO = checkUpkeepRecordDO;
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                if (!CAN_COMMIT.contains(finalCheckUpkeepRecordDO.getStatus())) {
                    throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
                }
                // 更新检保条目
                updateItem(checkUpkeepRecordDTO, finalCheckUpkeepRecordDO);
                // 修改检保单状态
                checkUpkeepRecordRepository.updateById(finalCheckUpkeepRecordDO);
                // 保存维修信息
                saveRepair(finalCheckUpkeepRecordDO);

                CheckUpkeepRecordRecheckDO checkUpkeepRecordRecheckDO =
                        CheckUpkeepRecordConvert.INSTANCE.buildRecordRecheck(finalCheckUpkeepRecordDO, CheckUpkeepRecordRecheck.HandlerType.CHECK_UPKEEP);
                checkUpkeepRecordRecheckDO.setHandleOpRemark(CheckUpkeepRecordRecheck.HandleOpRemark.CHECK_UPKEEP_REPAIR_COMMIT.getDesc());
                checkUpkeepRecordRecheckRepository.insert(checkUpkeepRecordRecheckDO);
            }
        });
        // 发送审核消息
        sendCheckUpkeepMessage(checkUpkeepRecordDO, type, CheckUpkeepStatusEnum.RECHECKING.getType());
        // 发送维修消息
        sendCheckUpkeepMessage(checkUpkeepRecordDO, CheckUpkeepMessageTypeEnum.REPAIR.getType(), CheckUpkeepStatusEnum.RECHECKING.getType());

    }

    /**
     * 复核提交
     *
     * @param recheckCommitDTO
     */
    @Override
    public void recheckCommit(RecheckCommitDTO recheckCommitDTO) {
        CheckUpkeepRecordDO upkeepRecordDO = checkUpkeepRecordRepository.getById(recheckCommitDTO.getId());
        if (upkeepRecordDO == null || !CAN_RECHECK.contains(upkeepRecordDO.getStatus())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        commitCheckUser(upkeepRecordDO);
        upkeepRecordDO.setArchiveUserId(recheckCommitDTO.getArchiveUserId());
        upkeepRecordDO.setArchiveUserName(recheckCommitDTO.getArchiveUserName());
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                if (!CAN_RECHECK.contains(upkeepRecordDO.getStatus())) {
                    throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
                }
                // 更新检保记录
                upkeepRecordDO.setStatus(CheckUpkeepStatusEnum.PASSED.getType());
                checkUpkeepRecordRepository.updateById(upkeepRecordDO);
                CheckUpkeepRecordRecheckDO checkUpkeepRecordRecheckDO = CheckUpkeepRecordConvert.INSTANCE.buildRecordRecheck(upkeepRecordDO, CheckUpkeepRecordRecheck.HandlerType.CHECK_UPKEEP.RECHECK);
                checkUpkeepRecordRecheckDO.setRecheckSuggestion(recheckCommitDTO.getRecheckSuggestion());
                checkUpkeepRecordRecheckDO.setStatus(1);

                checkUpkeepRecordRecheckDO.setHandleOpRemark(CheckUpkeepRecordRecheck.HandleOpRemark.RECHECK_COMMIT.getDesc());
                checkUpkeepRecordRecheckRepository.insert(checkUpkeepRecordRecheckDO);
            }
        });
        // 发送待归档消息
        sendCheckUpkeepMessage(upkeepRecordDO, upkeepRecordDO.getType(), CheckUpkeepStatusEnum.PASSED.getType());

    }


    /**
     * 检保记录复核驳回
     *
     * @param turnDownReqDTO
     */
    @Override
    public void recheckTurnDown(CheckUpkeepRecordTurnDownReqDTO turnDownReqDTO) {
        CheckUpkeepRecordDO upkeepRecordDO = checkUpkeepRecordRepository.getById(turnDownReqDTO.getId());
        if (upkeepRecordDO == null) {
            throw new BusinessException(BizErrorEnums.NOT_DATA);
        }
        if (!CAN_RECHECK.contains(upkeepRecordDO.getStatus())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        commitCheckUser(upkeepRecordDO);
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                if (!CAN_RECHECK.contains(upkeepRecordDO.getStatus())) {
                    throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
                }
                // 更新检保记录
                upkeepRecordDO.setStatus(CheckUpkeepStatusEnum.TURN_DOWN.getType());
                checkUpkeepRecordRepository.updateById(upkeepRecordDO);
                CheckUpkeepRecordRecheckDO checkUpkeepRecordRecheckDO = CheckUpkeepRecordConvert.INSTANCE.buildRecordRecheck(upkeepRecordDO, CheckUpkeepRecordRecheck.HandlerType.RECHECK);
                checkUpkeepRecordRecheckDO.setRecheckSuggestion(turnDownReqDTO.getRecheckSuggestion());
                checkUpkeepRecordRecheckDO.setStatus(0);
                checkUpkeepRecordRecheckDO.setHandleOpRemark(CheckUpkeepRecordRecheck.HandleOpRemark.RECHECK_TURN_DOWN.getDesc());
                // 保存复核记录
                checkUpkeepRecordRecheckRepository.insert(checkUpkeepRecordRecheckDO);
                // 删除维修单
                eqpRepairRepository.deleteByRecordId(upkeepRecordDO.getId());
                // 删除维修消息
                checkUpkeepMessageRepository.deleteByRecordId(upkeepRecordDO.getId(), CheckUpkeepMessageTypeEnum.REPAIR.getType());
            }
        });
        // 发送已驳回消息
        sendCheckUpkeepMessage(upkeepRecordDO, upkeepRecordDO.getType(), CheckUpkeepStatusEnum.TURN_DOWN.getType());
    }

    @Override
    public void archiveCommit(ArchiveCommitDTO archiveCommitDTO) {
        CheckUpkeepRecordDO upkeepRecordDO = checkUpkeepRecordRepository.getById(archiveCommitDTO.getId());
        if (upkeepRecordDO == null) {
            throw new BusinessException(BizErrorEnums.NOT_DATA);
        }
        if (!CheckUpkeepStatusEnum.PASSED.getType().equals(upkeepRecordDO.getStatus())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        SsoLoginUser ssoLoginUser = AuthSsoContext.getSsoLoginUser();
        if (!upkeepRecordDO.getArchiveUserId().equals(ssoLoginUser.getUserId())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        upkeepRecordDO.setArchiveUserId(ssoLoginUser.getUserId());
        upkeepRecordDO.setArchiveUserName(ssoLoginUser.getUserName());
        upkeepRecordDO.setArchiveCommitTime(new Date());
        upkeepRecordDO.setStatus(CheckUpkeepStatusEnum.ARCHIVIST.getType());
        checkUpkeepRecordRepository.updateById(upkeepRecordDO);
        CheckUpkeepRecordRecheckDO checkUpkeepRecordRecheckDO = CheckUpkeepRecordConvert.INSTANCE.buildRecordRecheck(upkeepRecordDO, CheckUpkeepRecordRecheck.HandlerType.ARCHIVE);
        checkUpkeepRecordRecheckDO.setHandleOpRemark(CheckUpkeepRecordRecheck.HandleOpRemark.ARCHIVE_COMMIT.getDesc());
        checkUpkeepRecordRecheckDO.setStatus(1);
        checkUpkeepRecordRecheckRepository.insert(checkUpkeepRecordRecheckDO);
    }

    private SsoLoginUser commitCheckUser(CheckUpkeepRecordDO upkeepRecordDO) {
        SsoLoginUser ssoLoginUser = AuthSsoContext.getSsoLoginUser();
        if (!upkeepRecordDO.getRecheckUserId().equals(ssoLoginUser.getUserId())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        upkeepRecordDO.setRecheckUserId(ssoLoginUser.getUserId());
        upkeepRecordDO.setRecheckUserName(ssoLoginUser.getUserName());
        upkeepRecordDO.setRecheckCommitDate(new Date());

        return ssoLoginUser;
    }

    @Override
    public void archiveTurnDown(ArchiveTurnDownDTO archiveTurnDownDTO) {
        CheckUpkeepRecordDO upkeepRecordDO = checkUpkeepRecordRepository.getById(archiveTurnDownDTO.getId());
        if (upkeepRecordDO == null) {
            throw new BusinessException(BizErrorEnums.NOT_DATA);
        }
        if (!CheckUpkeepStatusEnum.PASSED.getType().equals(upkeepRecordDO.getStatus())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }

        SsoLoginUser ssoLoginUser = AuthSsoContext.getSsoLoginUser();
        if (!upkeepRecordDO.getArchiveUserId().equals(ssoLoginUser.getUserId())) {
            throw new BusinessException(BizErrorEnums.NO_AUTH_OPERATION);
        }
        upkeepRecordDO.setArchiveUserId(ssoLoginUser.getUserId());
        upkeepRecordDO.setArchiveUserName(ssoLoginUser.getUserName());
        upkeepRecordDO.setArchiveCommitTime(new Date());
        upkeepRecordDO.setStatus(CheckUpkeepStatusEnum.ARCHIVIST_TURN_DOWN.getType());
        checkUpkeepRecordRepository.updateById(upkeepRecordDO);
        CheckUpkeepRecordRecheckDO checkUpkeepRecordRecheckDO = CheckUpkeepRecordConvert.INSTANCE.buildRecordRecheck(upkeepRecordDO, CheckUpkeepRecordRecheck.HandlerType.ARCHIVE);
        checkUpkeepRecordRecheckDO.setHandleOpRemark(CheckUpkeepRecordRecheck.HandleOpRemark.ARCHIVE_TURN_DOWN.getDesc());
        checkUpkeepRecordRecheckDO.setStatus(0);
        checkUpkeepRecordRecheckRepository.insert(checkUpkeepRecordRecheckDO);
        sendCheckUpkeepMessage(upkeepRecordDO, upkeepRecordDO.getType(), CheckUpkeepStatusEnum.ARCHIVIST_TURN_DOWN.getType());

    }

    @Override
    public void checkUpkeepArchive(CheckUpkeepArchiveDTO checkUpkeepArchiveDTO) {
        Date startDateByMonth = DateUtils.getStartDateByMonth(checkUpkeepArchiveDTO.getYearMonth());
        Date endDateByMonth = DateUtils.getEndDateByMonth(checkUpkeepArchiveDTO.getYearMonth());
        checkUpkeepRecordRepository.updateCheckUpkeepRecordArchive(checkUpkeepArchiveDTO.getType(), startDateByMonth, endDateByMonth);
    }

    @Override
    public CheckArchiveVO checkArchiveList(String yearMonth) {
        CheckArchiveVO checkArchiveVO = new CheckArchiveVO();
        Date startDateByMonth = DateUtils.getStartDateByMonth(yearMonth);
        Date endDateByMonth = DateUtils.getEndDateByMonth(yearMonth);
        // 获取某一月的检保任务
        List<CheckUpkeepRecordDO> checkUpkeepRecordDOList = checkUpkeepRecordRepository.selectCheckUpkeepStatus(startDateByMonth, endDateByMonth,
                CheckUpkeepTypeEnum.CHECK.getType());
        // 获取某一月的通过的假期申请
        List<HolidayApplyDO> holidayApplyDOList = holidayApplyRepository.selectByDateAndType(startDateByMonth, endDateByMonth, CheckUpkeepTypeEnum.CHECK.getType());
        Map<Date, HolidayApplyDO> holidayApplyDOMap = holidayApplyDOList.stream().collect(Collectors.toMap(HolidayApplyDO::getStartTime, Function.identity(), (a, b) -> a));
        if (!CollectionUtils.isEmpty(checkUpkeepRecordDOList)) {
            List<CheckArchiveVO.CheckStatusVO> checkStatusList = new ArrayList<>();
            Map<Date, List<CheckUpkeepRecordDO>> dateListMap = checkUpkeepRecordDOList.stream().collect(Collectors.groupingBy(CheckUpkeepRecordDO::getCheckUpkeepStartTime));
            dateListMap.forEach((k, v) -> {
                CheckArchiveVO.CheckStatusVO checkStatusVO = new CheckArchiveVO.CheckStatusVO();
                checkStatusVO.setDate(k);
                CheckUpkeepRecordDO passed = v.stream().filter(one -> one.getStatus().equals(CheckUpkeepStatusEnum.PASSED.getType())).findFirst().orElse(null);
                CheckUpkeepRecordDO archivist = v.stream().filter(one -> one.getStatus().equals(CheckUpkeepStatusEnum.ARCHIVIST.getType())).findFirst().orElse(null);
                CheckUpkeepRecordDO no_commit = v.stream().filter(one -> one.getStatus().equals(CheckUpkeepStatusEnum.NO_COMMIT.getType())).findFirst().orElse(null);
                HolidayApplyDO holidayApplyDO = holidayApplyDOMap.get(k);
                // 假期>未提交>已通过>已归档
                if (holidayApplyDO != null) {
                    checkStatusVO.setStatus("holiday");
                    checkStatusVO.setInfo("假期");
                } else if (no_commit != null) {
                    checkStatusVO.setStatus(CheckUpkeepStatusEnum.NO_COMMIT.getType());
                    checkStatusVO.setInfo(CheckUpkeepStatusEnum.NO_COMMIT.getDesc());
                } else if (passed != null) {
                    checkStatusVO.setStatus(CheckUpkeepStatusEnum.PASSED.getType());
                    checkStatusVO.setInfo(CheckUpkeepStatusEnum.PASSED.getDesc());
                } else if (archivist != null) {
                    checkStatusVO.setStatus(CheckUpkeepStatusEnum.ARCHIVIST.getType());
                    checkStatusVO.setInfo(CheckUpkeepStatusEnum.ARCHIVIST.getDesc());
                }
                checkStatusList.add(checkStatusVO);
            });
            checkArchiveVO.setCheckStatusList(checkStatusList);
        }
        return checkArchiveVO;
    }

    @Override
    public List<UpkeepArchiveVO> upkeepArchiveList(String yearMonth) {
        List<UpkeepArchiveVO> upkeepArchiveVOS = new ArrayList<>();
        Date startTime = new Date();
        Date endTime = new Date();

        if (StringUtils.isNotBlank(yearMonth)) {
            startTime = DateUtils.getStartDateByMonth(yearMonth);
            endTime = DateUtils.getEndDateByMonth(yearMonth);
        } else {
            Date date = new Date();
            Date endDateByWeek = DateUtils.getEndDateByWeek(date);
            endTime = DateUtils.getEndDate(endDateByWeek);
            Date startDay = DateUtils.addDays(endDateByWeek, -21);
            startTime = DateUtils.getStartDate(startDay);
        }
        // 最近三周保养任务单
        List<CheckUpkeepRecordDO> checkUpkeepRecordDOS = checkUpkeepRecordRepository.selectCheckUpkeepStatus(startTime, endTime, CheckUpkeepTypeEnum.UPKEEP.getType());
        if (CollectionUtils.isEmpty(checkUpkeepRecordDOS)) {
            return upkeepArchiveVOS;
        }
        // 最近三周的假期申请
        List<HolidayApplyDO> holidayApplyDOS = holidayApplyRepository.selectByDateAndType(startTime, endTime, CheckUpkeepTypeEnum.UPKEEP.getType());
        Map<Date, HolidayApplyDO> holidayApplyDOMap = holidayApplyDOS.stream().collect(Collectors.toMap(HolidayApplyDO::getStartTime, Function.identity(), (a, b) -> a));
        Map<Date, List<CheckUpkeepRecordDO>> recordMap = checkUpkeepRecordDOS.stream().collect(Collectors.groupingBy(CheckUpkeepRecordDO::getCheckUpkeepStartTime));
        recordMap.forEach((k, v) -> {
            UpkeepArchiveVO upkeepArchiveVO = new UpkeepArchiveVO();
            upkeepArchiveVO.setWeek("第" + DateUtils.whatWeekByDate(k) + "周");
            upkeepArchiveVO.setWeekStartTime(k);
            Date endDay = DateUtils.addDays(k, 7);
            Date endDate = DateUtils.getEndDate(endDay);
            upkeepArchiveVO.setWeekEndTime(endDate);
            CheckUpkeepRecordDO passed = v.stream().filter(one -> one.getStatus().equals(CheckUpkeepStatusEnum.PASSED.getType())).findFirst().orElse(null);
            CheckUpkeepRecordDO archivist = v.stream().filter(one -> one.getStatus().equals(CheckUpkeepStatusEnum.ARCHIVIST.getType())).findFirst().orElse(null);
            CheckUpkeepRecordDO no_commit = v.stream().filter(one -> one.getStatus().equals(CheckUpkeepStatusEnum.NO_COMMIT.getType())).findFirst().orElse(null);
            HolidayApplyDO holidayApplyDO = holidayApplyDOMap.get(k);
            // 假期>未提交>已通过>已归档
            if (holidayApplyDO != null) {
                upkeepArchiveVO.setStatus("holiday");
                upkeepArchiveVO.setDesc("假期");
            } else if (no_commit != null) {
                upkeepArchiveVO.setStatus(CheckUpkeepStatusEnum.NO_COMMIT.getType());
                upkeepArchiveVO.setDesc(CheckUpkeepStatusEnum.NO_COMMIT.getDesc());
            } else if (passed != null) {
                upkeepArchiveVO.setStatus(CheckUpkeepStatusEnum.PASSED.getType());
                upkeepArchiveVO.setDesc(CheckUpkeepStatusEnum.PASSED.getDesc());
            } else if (archivist != null) {
                upkeepArchiveVO.setStatus(CheckUpkeepStatusEnum.ARCHIVIST.getType());
                upkeepArchiveVO.setDesc(CheckUpkeepStatusEnum.ARCHIVIST.getDesc());
            }
            upkeepArchiveVOS.add(upkeepArchiveVO);
        });
        return upkeepArchiveVOS;
    }

    /**
     * app端 检保任务详情
     *
     * @param recordAppDTO
     * @return
     */
    @Override
    public CheckUpkeepRecordAppVO getCheckUpkeepRecordDetailApp(CheckUpkeepRecordIdDTO recordAppDTO) {
        CheckUpkeepRecordDO checkUpkeepRecordDO = null;
        if (StringUtils.isNotBlank(recordAppDTO.getCheckUpkeepRecordId())) {
            // 如果有检保记录id，根据id查询
            checkUpkeepRecordDO = checkUpkeepRecordRepository.getById(recordAppDTO.getCheckUpkeepRecordId());
        }
        // 如果没有ID根据  设备编号、类型和当前日期查询
        if (Objects.isNull(checkUpkeepRecordDO) && StringUtils.isNotBlank(recordAppDTO.getEqpCode()) && StringUtils.isNotBlank(recordAppDTO.getType())) {
            checkUpkeepRecordDO = checkUpkeepRecordRepository.getByEqpCodeAndTypeAndCheckUpkeepDate(recordAppDTO.getEqpCode(), recordAppDTO.getType(), new Date());
        }
        if (Objects.isNull(checkUpkeepRecordDO)) {
            throw new BusinessException(BizErrorEnums.NOT_DATA);
        }

        String checkUpkeepId = checkUpkeepRecordDO.getCheckUpkeepId();

        // 获取检保用户信息
        List<CheckUpkeepUserVO> checkUpUserVOList = checkUpkeepUserService.getCheckUpkeepUserVOList(checkUpkeepId, CheckUpkeepUserTypeEnum.CHECK.getType());
        // 获取复核用户信息
        List<CheckUpkeepUserVO> recheckUserVOList = checkUpkeepUserService.getCheckUpkeepUserVOList(checkUpkeepId, CheckUpkeepUserTypeEnum.RECHECK.getType());
        // 获取归档用户信息
        List<CheckUpkeepUserVO> auditUserVOList = checkUpkeepUserService.getCheckUpkeepUserVOList(checkUpkeepId, CheckUpkeepUserTypeEnum.ARCHIVIST.getType());
        CheckUpkeepRecordAppVO checkUpkeepRecordAppVO = CheckUpkeepRecordConvert.INSTANCE.do2AppVO(checkUpkeepRecordDO);
        checkUpkeepRecordAppVO.setCheckUserList(checkUpUserVOList);
        checkUpkeepRecordAppVO.setRecheckUserList(recheckUserVOList);
        checkUpkeepRecordAppVO.setArchiveUserList(auditUserVOList);
        hasEditAuth(checkUpkeepRecordAppVO);
        // 获取检保任务条目
        List<CheckUpkeepRecordItemVO> checkUpkeepRecordItemVOList = checkUpkeepRecordItemService.getByCheckUpkeepRecordId(checkUpkeepRecordDO.getId());
        if (!CollectionUtils.isEmpty(checkUpkeepRecordItemVOList)) {
            checkUpkeepRecordItemVOList.forEach(item -> {
                String imageUrl = item.getImageUrl();
                if (StringUtils.isNotBlank(imageUrl)) {
                    item.setImageList(Arrays.asList(imageUrl.split(",")));
                } else {
                    item.setImageList(new ArrayList<>());
                }
            });
            checkUpkeepRecordAppVO.setCheckUpkeepRecordItemList(checkUpkeepRecordItemVOList);
        }
        List<CheckUpkeepRecordRecheckDO> byCheckUpkeepRecordId = checkUpkeepRecordRecheckRepository.getByCheckUpkeepRecordIdAndHandleType(checkUpkeepRecordDO.getId(),
                CheckUpkeepRecordRecheck.HandlerType.RECHECK.getType());
        List<CheckUpkeepRecordRecheckRespVO> recheckRespVO = CheckUpkeepRecordConvert.INSTANCE.doRecheck2DTOList(byCheckUpkeepRecordId);
        checkUpkeepRecordAppVO.setRecheckRespList(recheckRespVO);
        //图片查询
        List<EqpAttachmentDO> attachmentDOS = eqpInfoRepository.getAttachmentByEqpId(checkUpkeepRecordDO.getEqpId(), AttachmentTypeEnum.IMAGE.getType(), 1);
        if (!CollectionUtils.isEmpty(attachmentDOS)) {
            checkUpkeepRecordAppVO.setImageUrl(attachmentDOS.get(0).getAttachmentUrl());
        }
        return checkUpkeepRecordAppVO;
    }

    private void updateItem(CheckUpkeepRecordDTO checkUpkeepRecordDTO, CheckUpkeepRecordDO checkUpkeepRecordDO) {
        SsoLoginUser ssoLoginUser = AuthSsoContext.getSsoLoginUser();
        checkUpkeepRecordDO.setCheckUpkeepUserId(ssoLoginUser.getUserId());
        checkUpkeepRecordDO.setCheckUpkeepUserName(ssoLoginUser.getUserName());
        checkUpkeepRecordDO.setStatus(CheckUpkeepStatusEnum.RECHECKING.getType());
        List<CheckUpkeepRecordItemDTO> checkUpkeepRecordItemDTOList = checkUpkeepRecordDTO.getCheckUpkeepRecordItemDTOList();
        AtomicReference<Integer> errResult = new AtomicReference<>(0);
        if (!CollectionUtils.isEmpty(checkUpkeepRecordItemDTOList)) {
            checkUpkeepRecordItemDTOList.forEach(checkUpkeepRecordItemDTO -> {
                if (checkUpkeepRecordItemDTO.getStatus() == null || checkUpkeepRecordItemDTO.getStatus() == 0) {
                    errResult.set(1);
                }
                List<String> imageList = checkUpkeepRecordItemDTO.getImageList();
                if (!CollectionUtils.isEmpty(imageList)) {
                    checkUpkeepRecordItemDTO.setImageUrl(String.join(",", imageList));
                }
            });
            List<CheckUpkeepRecordItemDO> checkUpkeepRecordItemDOS = CheckUpkeepRecordItemConvert.INSTANCE.dtoList2DO(checkUpkeepRecordItemDTOList);
            // 修改检保条目状态
            checkUpkeepRecordItemRepository.updateBatch(checkUpkeepRecordItemDOS);
        }
        checkUpkeepRecordDO.setErrResult(errResult.get());
    }

    private void saveRepair(CheckUpkeepRecordDO checkUpkeepRecordDO) {
        checkUpkeepRecordDO = checkUpkeepRecordRepository.getById(checkUpkeepRecordDO.getId());
        EqpRepairDO eqpRepairDO = new EqpRepairDO();
        eqpRepairDO.setId(IdGenerateUtils.getIdStr());
        eqpRepairDO.setCheckUpkeepId(checkUpkeepRecordDO.getCheckUpkeepId());
        eqpRepairDO.setCheckUpkeepRecordId(checkUpkeepRecordDO.getId());
        eqpRepairDO.setEqpId(checkUpkeepRecordDO.getEqpId());
        eqpRepairDO.setEqpName(checkUpkeepRecordDO.getEqpName());
        eqpRepairDO.setEqpCode(checkUpkeepRecordDO.getEqpCode());
        eqpRepairDO.setLineBody(checkUpkeepRecordDO.getLineBody());
        List<EqpAttachmentDO> eqpAttachmentDOS = eqpAttachmentRepository.getByEqpIdListAndType(Lists.newArrayList(checkUpkeepRecordDO.getEqpId()), AttachmentTypeEnum.IMAGE.getType());
        // 如果查询结果非空，则尝试获取并设置第一个附件的URL；否则，直接设置为null
        eqpRepairDO.setImageUrl(org.apache.commons.collections4.CollectionUtils.isNotEmpty(eqpAttachmentDOS)
                ? eqpAttachmentDOS.get(0).getAttachmentUrl()
                : "");
        eqpRepairDO.setStatus(0);
        eqpRepairDO.setUserId(checkUpkeepRecordDO.getCheckUpkeepUserId());
        eqpRepairDO.setUserName(checkUpkeepRecordDO.getCheckUpkeepUserName());
        // eqpRepairRepository.saveBatch(Lists.newArrayList(eqpRepairDO));
        eqpRepairRepository.insert(eqpRepairDO);
    }

    // 审核人员发送审核消息
    @Async(DEVICE_THREAD_POOL_EXECUTOR)
    public void sendCheckUpkeepMessage(CheckUpkeepRecordDO checkUpkeepRecordDO, String type, String status) {
        // 发送检保消息
        CheckUpkeepMessageDO checkUpkeepMessageDO = new CheckUpkeepMessageDO();
        checkUpkeepMessageDO.setId(IdGenerateUtils.getIdStr());
        checkUpkeepMessageDO.setCheckUpkeepId(checkUpkeepRecordDO.getCheckUpkeepId());
        checkUpkeepMessageDO.setCheckUpkeepRecordId(checkUpkeepRecordDO.getId());
        checkUpkeepMessageDO.setEqpName(checkUpkeepRecordDO.getEqpName());
        checkUpkeepMessageDO.setType(type);
        // 审核中
        if (CheckUpkeepStatusEnum.RECHECKING.getType().equals(status)) {
            // 维修人员目前为点检人员
            if (CheckUpkeepMessageTypeEnum.REPAIR.getType().equals(type)) {
                checkUpkeepMessageDO.setUserId(checkUpkeepRecordDO.getCheckUpkeepUserId());
                checkUpkeepMessageDO.setUserName(checkUpkeepRecordDO.getCheckUpkeepUserName());
            } else {
                checkUpkeepMessageDO.setUserId(checkUpkeepRecordDO.getRecheckUserId());
                checkUpkeepMessageDO.setUserName(checkUpkeepRecordDO.getRecheckUserName());
            }
            // 已通过
        } else if (CheckUpkeepStatusEnum.PASSED.getType().equals(status)) {
            checkUpkeepMessageDO.setUserId(checkUpkeepRecordDO.getArchiveUserId());
            checkUpkeepMessageDO.setUserName(checkUpkeepRecordDO.getArchiveUserName());
            // 已驳回
        } else if (CheckUpkeepStatusEnum.TURN_DOWN.getType().equals(status)) {
            checkUpkeepMessageDO.setUserId(checkUpkeepRecordDO.getCheckUpkeepUserId());
            checkUpkeepMessageDO.setUserName(checkUpkeepRecordDO.getCheckUpkeepUserName());
        } else if (CheckUpkeepStatusEnum.ARCHIVIST_TURN_DOWN.getType().equals(status)) {
            checkUpkeepMessageDO.setUserId(checkUpkeepRecordDO.getRecheckUserId());
            checkUpkeepMessageDO.setUserName(checkUpkeepRecordDO.getRecheckUserName());
        }
        checkUpkeepMessageDO.setSendTime(new Date());
        checkUpkeepMessageDO.setStatus(status);
        checkUpkeepMessageDO.setIsRead(0);
        checkUpkeepMessageDO.setCheckUpkeepDate(checkUpkeepRecordDO.getCheckUpkeepDate());
        try {
            checkUpkeepMessageRepository.saveBatch(Lists.newArrayList(checkUpkeepMessageDO));
        } catch (Exception e) {
            log.error("消息保存发生异常", e);
            // throw new BusinessException(500, "发送审核消息失败！");
        }
    }

    /**
     * 根据检保任务id查询检保任务详情
     *
     * @param checkUpkeepRecordId
     * @return
     */
    @Override
    public CheckUpkeepRecordVO getByCheckUpkeepRecordId(String checkUpkeepRecordId) {
        // 获取检保任务基本信息
        CheckUpkeepRecordDO checkUpkeepRecordDO = checkUpkeepRecordRepository.getById(checkUpkeepRecordId);
        if (ObjectUtils.isEmpty(checkUpkeepRecordDO)) {
            return null;
        }
        // DO -->VO
        CheckUpkeepRecordVO checkUpkeepRecordVO = CheckUpkeepRecordConvert.INSTANCE.do2VO(checkUpkeepRecordDO);

        // 获取检保任务条目
        List<CheckUpkeepRecordItemVO> checkUpkeepRecordItemVOList = checkUpkeepRecordItemService.getByCheckUpkeepRecordId(checkUpkeepRecordId);
        if (!CollectionUtils.isEmpty(checkUpkeepRecordItemVOList)) {
            checkUpkeepRecordItemVOList.forEach(item -> {
                String imageUrl = item.getImageUrl();
                if (StringUtils.isNotBlank(imageUrl)) {
                    item.setImageList(Arrays.asList(imageUrl.split(",")));
                }
            });
            checkUpkeepRecordVO.setCheckUpkeepRecordItemVOList(checkUpkeepRecordItemVOList);
        }
        // 获取检保任务复核信息
        List<CheckUpkeepRecordRecheckVO> checkUpkeepRecordRecheckVOList = checkUpkeepRecordRecheckService.getByCheckUpkeepRecordId(checkUpkeepRecordId);
        checkUpkeepRecordVO.setCheckUpkeepRecordRecheckVOList(checkUpkeepRecordRecheckVOList);
        return checkUpkeepRecordVO;
    }

    /**
     * 分页查询检保任务信息
     *
     * @param checkUpkeepRecordListDTO
     * @return
     */
    @Override
    public PageResponse<CheckUpkeepRecordVO> pageList(CheckUpkeepRecordListDTO checkUpkeepRecordListDTO) {

        // 1,查询分页的信息
        IPage<CheckUpkeepRecordDO> page = checkUpkeepRecordRepository.page(checkUpkeepRecordListDTO.getPage(), checkUpkeepRecordListDTO.getPageSize(), checkUpkeepRecordListDTO);

        // 2，如果分页对象的记录列表不为空
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            // 3,如果分页对象的记录列表为空
            return new PageResponse<>(0, null, checkUpkeepRecordListDTO);
        }

        // 4,将查询到的数据转换为VO
        List<CheckUpkeepRecordVO> checkUpkeepRecordVOList = CheckUpkeepRecordConvert.INSTANCE.dos2VOS(page.getRecords());

        // 1,先将状态为未提交的数据查询出来 返回的符合条件的Map集合，集合中存储的是所有未提交的数据（检保项目编号）
        List<String> checkUpkeepIds =
                checkUpkeepRecordVOList.stream()
                        .filter(record -> record.getStatus().equals(CheckUpkeepStatusEnum.NO_COMMIT.getType()))
                        .map(CheckUpkeepRecordVO::getCheckUpkeepId)
                        .collect(Collectors.toList());
        // 判断checkUpkeepIds是否为空
        if (CollectionUtils.isEmpty(checkUpkeepIds)) {
            // 2,如果checkUpkeepIds集合为空
            return new PageResponse<>(page.getTotal(), checkUpkeepRecordVOList, checkUpkeepRecordListDTO);
        }
        // 根据检保项目List以及人员类型，查询到对应的检保人员
        List<CheckUpkeepUserDO> checkUpkeepUserDOS = checkUpkeepUserRepository.getCheckUserByCheckUpkeepIds(checkUpkeepIds, CheckUpkeepUserTypeEnum.CHECK.getType());
        Map<String, List<CheckUpkeepUserDO>> checkUserMap;
        if (!CollectionUtils.isEmpty(checkUpkeepUserDOS)) {
            // 根据检保项目编号分类存储  得到的是一个map集合
            checkUserMap = checkUpkeepUserDOS.stream().collect(Collectors.groupingBy(CheckUpkeepUserDO::getCheckUpkeepId));
        } else {
            checkUserMap = new HashMap<>();
        }

        checkUpkeepRecordVOList.forEach(checkUpkeepRecordVO -> {
                    List<CheckUpkeepUserDO> checkUpkeepUserDOList = checkUserMap.get(checkUpkeepRecordVO.getCheckUpkeepId());
                    if (!CollectionUtils.isEmpty(checkUpkeepUserDOList)) {
                        List<CheckUpkeepUserVO> checkUpkeepUserVOList = CheckUpkeepUserConvert.INSTANCE.toVOList(checkUpkeepUserDOList);
                        checkUpkeepRecordVO.setCheckUpkeepUserVOList(checkUpkeepUserVOList);
                    }
                }
        );
        return new PageResponse<>(page.getTotal(), checkUpkeepRecordVOList, checkUpkeepRecordListDTO);
    }
}
